﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using DapperWrapper;
using ZilLion.Service.Core.DapperWrapper;
using ZilLion.Service.Core.ModelBase;

namespace ZLWeb.WebApiRepository.Base
{
    public class SqlConnectionLoader
    {
        static readonly SqlConnectionRepository sqlConnectionRepository = new SqlConnectionRepository();
        public static List<ICRMDbContext> ReadDbContextList { get; set; }
        public static List<ICRMDbContext> WriteReadDbContextList { get; set; }
        private static int GroupVersion { get; set; }

        public static void SetContext(IDbContext Context)
        {
            sqlConnectionRepository.SetDbContext(Context);
        }

        public static void LoadCheckDbConnections()
        {
            TaskFactory tf = new TaskFactory();
            Task task1 = tf.StartNew(CheckConnections);
        }

        public static int GetConnectionsCount()
        {
            return ReadDbContextList.Count;
        }

        public static void CheckConnections()
        {
            try
            {
                while (true)
                {
                    Thread.Sleep(20000);
                    int GroupVersion2=sqlConnectionRepository.CheckConnections(GroupVersion);
                    if (GroupVersion2> GroupVersion)
                    {
                        GroupVersion = GroupVersion2;
                        LoadSqlConnections();
                    }
                }
            }
            catch (Exception ex)
            {

            }
        }

        public static void LoadSqlConnections()
        {
            var item = sqlConnectionRepository.GetDBConnections();
            GroupVersion = item.Item2;
            ReadDbContextList = item.Item1.ToList<ICRMDbContext>();
            WriteReadDbContextList = item.Item1.Where(tr => tr.mizhch == 1).ToList<ICRMDbContext>();
        }


        public SqlConnectionLoader(long accid)
        {
            this.hashcode = (Math.Abs(accid).ToString().GetHashCode());
        }

        public int hashcode { get; set; }

        private int Connectfactor { get; set; }
        public IDbContext GetDbContext()
        {
            if (WriteReadDbContextList.Count > 1)
            {
                Connectfactor = Math.Abs(hashcode%(WriteReadDbContextList.Count));
            }
            return DbContext;
        }

        private IDbContext _DbContext { get; set; }

        public IDbContext DbContext
        {
            get
            {
                if (_DbContext != null) return _DbContext;
                _DbContext = WriteReadDbContextList[Connectfactor];
                return _DbContext;
            }
        }
    }
}
